/**
 * core.js
 *
 * @members kaiye, alextang
 * @date 2011-03-24
 */

// extend query to HTMLDocumentS
HTMLDocument.prototype.$ = function (selector) {
    return this.querySelector(selector) ;
}
HTMLDocument.prototype.$$ = function (selector) {
    return this.querySelectorAll(selector) ;
}
$ = function (selector) {
    return document.querySelector(selector) ;
}
$$ = function (selector) {
    return document.querySelectorAll(selector) ;
}



// event
$addEvent = function(el,type,fn){
    if(!el) return false ;
	el.addEventListener(type,fn,false);
}

// class operation
$hasClass = function (obj, newClass) {
    var objClassName = obj.className,
        s = ' ';
    return (s + objClassName + s).indexOf(s + newClass + s) != -1;
}
$addClass = function(obj, newClass) {
    if (!$hasClass(obj, newClass)){
        obj.className = obj.className + ' ' + newClass ;
    }
}
$removeClass = function(obj, oldClass) {
    if ($hasClass(obj, oldClass)){
        var s = ' ' ;
        obj.className = ((s + obj.className + s).replace((s + oldClass + s), s)).trim() ;
    }
}
$replaceClass = function(obj, oldClass, newClass) {
    if ($hasClass(obj, oldClass)){
        var s = ' ' ;
        obj.className = ((s + obj.className + s).replace((s + oldClass + s), s + newClass + s)).trim() ;
    }
}
$toggleClass = function(obj, class1, class2) {
    ($hasClass(obj, class1)) ? $replaceClass(obj, class1, class2) : $replaceClass(obj, class2, class1);
}
$showEl = function (el, clsName) {
    $removeClass(el, clsName || 'hide'); 
}
$hideEl = function (el, clsName) {
    $addClass(el, clsName || 'hide');
}

// extend each to NodeList (Array-like Object)
if (!NodeList.prototype.each) {
    NodeList.prototype.each = function(fun) {
        var len = this.length;
        if (typeof fun != "function")
        throw new TypeError();

        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this)
            fun.call(thisp, this[i], i, this);
        }
    };
}

// onDOMReady
$ready = function (fn) {
    window.onload = function () {
        fn();
    }
    // var isReady = function () {
        // if (document.readyState !== 'interactive' || document.readyState !== 'complete') {
            // setTimeout(isReady, 16);
        // }else {
            // fn();
        // }
    // }
    // isReady();
}

// Ajax 
var __Ajax={
    create:function (){
        var obj = null;	
        try{
            obj = new ActiveXObject('Msxml2.XMLHTTP');
        }catch(e){
            try{
                obj = new ActiveXObject('Microsoft.XMLHTTP');
            }catch(e){
                obj = new XMLHttpRequest();
            }
        }
        return obj;
    },
    Request: function (){
        if(arguments.length<2)return ;
        var _x= this.create(); 
        var para = {asynchronous:true,method:"GET",parameters:""};
        for (var key in arguments[1]){
            para[key] = arguments[1][key];
        }
        var _url=arguments[0];
        _x.open(para["method"].toUpperCase(),_url,para["asynchronous"]);
        var _self = this ;
        _x.onreadystatechange = function () {
            _self.onStateChange(this,para);
        }
        //post
        if(para["method"].toUpperCase()=="POST"){
            _x.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        }
        for (var ReqHeader in para["setRequestHeader"]){
            _x.setRequestHeader(ReqHeader,para["setRequestHeader"][ReqHeader]);
        }
        _x.send(para["method"].toUpperCase()=="POST"?(para["postBody"]?para["postBody"]:para["parameters"]):null);
        return _x;
    },
    onStateChange: function(o, para){
        if(o.readyState==4){
            if(o.status==200)
                para["onComplete"]?para["onComplete"](o):"";
            else{
                para["onError"]?para["onError"](o):"";
            }
        }
    },
    q: function (data){
        var data = this.format(data) ;
        return this.Request(data.url, {method: data.method || "get", parameters: data.para || "", onComplete: data.success, onError: data.error });
    },
    format: function (data) {
        var symbol = '',
            params = '';
        for (var i in data.params) {
            params += symbol + i + '=' + data.params[i] ;
            symbol = '&' ;
        }

        if (data.method.toLowerCase() == 'get') {
            params += (params.length > 0 ? '&':'' ) + 't=' + Math.floor(Math.random()*100000) ;
            data.url += (data.url.indexOf('?') == -1 ? '?' : '&') + params ;
        }else {
            data.para = params ;
        }
        return data ;
    }
};

$Ajax = function (data) {
    return __Ajax.q(data); 
}

// 关闭浮层
var closeLayer = function (aEl, tagClose, callback) {
    for (var i = 0, k ; k = aEl[i] ; i++ ) {
        var el = $$(k + ' '+ tagClose);
        for (var ii = 0, kk ; kk = el[ii] ; ii++ ) {
            kk.pNode = k ;
            $addEvent(kk, 'click', function () {
                $addClass($(this.pNode), 'hide');
                callback && callback();
            })
        }
    }
}

